#服务数据总计服务类  flydragon
class StatisticalDatum::ServiceTotalService
  include HeiPisService

  #company 单位
  #studio 分店
  def initialize(company, studio)
    @company = company
    @studio = studio
  end


  #执行方法 返回值
  def call

    #=======最近30天数据=======#

    filter_params = {:company_id => @company.id }
    filter_params[:start_date] = Date.current - 30.day
    filter_params[:end_date] = Date.current

    sql_where = " where studios.company_id = :company_id and (ord.created_at between :start_date and :end_date) "
    if @studio.present?
      filter_params[:studio_id] = @studio.id 
      sql_where += " and ord.studio_id = :studio_id"
    end

    sql = %Q{
      select sum(ord.total_price) as sale_amount,
      date_format(ord.created_at,'%Y-%m-%d') as created_date 
      from orders ord join studios on ord.studio_id = studios.id
      #{sql_where} 
      group by created_date
    }

    #将汇总的信息转化成hash 日期为key 销售额为value
    sale_info = {}
    Order.find_by_sql([sql,filter_params]).each do |record|
      sale_info[record.created_date] = record.sale_amount
    end

    #时间数组
    dates = []
    #销售额度数组
    sale_amounts =[]

    for day in ((Date.current - 30.day)..Date.current)

      date_str = day.strftime('%Y-%m-%d')
      dates << date_str
     sale_amounts << (sale_info[date_str].present? ? sale_info[date_str] : 0)
    end

    Result.new(dates,sale_amounts)
  end

  #内部类,指定结果返回值
  class Result
  	attr_reader :dates, :sale_amounts,:total_amount

    #dates 日期数组
    #sale_amounts 销售额度列表信息
	  def initialize(dates, sale_amounts)
      @dates = dates
      @sale_amounts = sale_amounts
      @total_amount = sale_amounts.inject{ |result, element| result + element }
    end 

  end

end
